
#include "uart_util.h"
#include "usart.h"
#include "remote_periph.h"
#include "imu_periph.h"
/********** VOLATILE USER CODE **********/


void Uart_RxIdleCallback(UART_HandleTypeDef* huart) {
    /* clear idle it flag avoid idle interrupt all the time */
    __HAL_UART_CLEAR_IDLEFLAG(huart);

    /* handle received data in idle interrupt */
    if (huart == Const_Remote_UART_HANDLER) {
        Remote_RXCallback(huart);
    }
    else if (huart == Const_IMU_UART_HANDLER) {
        IMU_RXCallback(huart);
    }


}

/********** VOLATILE USER CODE END **********/


void Uart_SendMessage(UART_HandleTypeDef* huart, uint8_t txdata[], uint16_t size, uint32_t timeout) {
    /* Start the Transmission process */
    uint32_t ret = HAL_UART_Transmit(huart, txdata, size, timeout);
    if (ret != HAL_OK) {
        /* Transmission request Error */
        Uart_ErrorHandler(ret);
    }
}


void Uart_SendMessage_IT(UART_HandleTypeDef* huart, uint8_t txdata[], uint16_t size) {
    /* Start the Transmission process */
    uint32_t ret = HAL_UART_Transmit_IT(huart, txdata, size);
    if (ret != HAL_OK) {
        /* Transmission request Error */
        Uart_ErrorHandler(ret);
    }
}


void Uart_SendMessage_IT_Force(UART_HandleTypeDef* huart, uint8_t txdata[], uint16_t size, uint32_t timeout) {
    /* Start the Transmission process */
    uint32_t now = HAL_GetTick();
    uint32_t ret;
    do {
        ret = HAL_UART_Transmit_IT(huart, txdata, size);
    } while (ret != HAL_OK && HAL_GetTick() - now <= timeout);
    if (ret != HAL_OK) {
        /* Transmission request Error */
        Uart_ErrorHandler(ret);
    }
}


void Uart_ErrorHandler(uint32_t ret) {
    //Log_DebugPrintf("Error: UART Error: %d!\n", ret);
    while (1) {
        return;
    }
}


void Uart_ReceiveHandler(UART_HandleTypeDef *huart) {
    if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) && __HAL_UART_GET_IT_SOURCE(huart, UART_IT_IDLE)) {
        Uart_RxIdleCallback(huart);
    }
}
